const express = require('express')
const router = express.Router()

const Admin = require('../Model/Admin')
const getter = require('../middleware/AutoToken').getter

router
  .put('/admin', (req, res, next) => {
    const admin = req.body
    if (admin.username && admin.password && admin.newPassword) {
      Admin.findOne({ username: admin.username }, (err, doc) => {
        if (err || !doc) {
          res.hasError(404, '更新失败，用户不存在')
        } else if (doc.password !== res.solt(admin.password)) {
          res.hasError(404, '原密码错误')
        } else {
          doc.password = res.solt(admin.newPassword)
          doc.save((err, doc) => {
            if (err) {
              res.hasError(404, '更新失败，系统错误', err)
            } else {
              res.success('更新成功')
            }
          })
        }
      })
    } else {
      res.hasError(404, '请求参数缺失')
    }
  })
  .post('/admin', (req, res, next) => {
    const admin = req.body
    if (!admin.username || !admin.password) {
      res.hasError('创建失败:用户名密码不能为空')
    } else {
      Admin.findOne({ username: admin.username }, (err, doc) => {
        if (!err && doc) {
          res.hasError('该管理员已存在')
        } else {
          Admin.create({
            username: admin.username,
            password: res.solt(admin.password)
          }, (err, doc) => {
            if (err) {
              res.hasError('系统错误')
            } else {
              doc.password = ''
              res.success('创建成功', doc)
            }
          })
        }
      })
    }
  })

  .get('/admin', (req, res, next) => {
    res.success('hello')
  })

  .delete('/admin', (req, res, next) => {

  })

module.exports = router